import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login'
import Home from '@/components/Home'
import Welcome from '@/components/Welcome'
import User from '@/components/User'
import Rights from '@/components/power/Rights'
import Roles from '@/components/power/Roles'
import shiyan from '@/components/shiyam'
import Cate from '@/components/goods/Cate'
import List from '@/components/goods/List'
import Params from '@/components/goods/Params'
import Add from '@/components/goods/Add'
import Orers from '@/components/order/Orders'
import Report from '@/components/report/Report'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { path: '/shiyan', component: shiyan },
    {
      path: '/home',
      component: Home,
      redirect: '/home/welcome',
      children: [
        { path: 'welcome', component: Welcome },
        { path: 'users', component: User },
        { path: 'rights', component: Rights },
        { path: 'roles', component: Roles },
        { path: 'categories', component: Cate },
        { path: 'goods', component: List },
        { path: 'params', component: Params },
        { path: 'goods/add', component: Add },
        { path: 'orders', component: Orers },
        { path: 'reports', component: Report }
      ]
    }
  ]
})
// 为对象添加路由守卫
router.beforeEach((to, from, next) => {
  // 如果访问的是登录页 则直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage获取到token值
  const token = sessionStorage.getItem('token')
  // 判断sessionStorage里面有没有token
  if (!token) return next('/login')
  next()
})
export default router

// 第一种方法
/* if (to.path === '/home') {
    const token = sessionStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  } */
